
#include"user_system.h"
UserNode *head1;

/*
** 功能：初始化用户列表
*/ 
UserNode *user_list_init(void)
{
	UserNode *head = (UserNode *)malloc(sizeof(UserNode));
	if( head == NULL)
	{
		perror("user_list_init malloc fail");
		exit(1);
	}
	
	head->next = head;
	head->prev = head;
	
	return head;
}

/*
** 功能：注册新用户
** head：用户链表
** user：用户名
** pass：密码
** 返回值：
** 		：成功 1
** 		：失败 0
*/ 
int user_register(UserNode *head, const char *user, const char *pass)
{
	// 检查用户是否存在
	UserNode *tmp = head->next;
	while( tmp != head )
	{
		if( strncmp(tmp->username, user,sizeof(user)) == 0 )
			return 0;
		tmp = tmp->next;
	}
	
	// 创建新用户
	UserNode *new = (UserNode *)calloc(1, sizeof(UserNode));
	if( new == NULL)
    {
        perror("创建新用户发生calloc失败");
        return 0;
    }
		
	
	strncpy(new->username, user, MAX_USERNAME_LEN-1);
	strncpy(new->password, pass, MAX_PASSWORD_LEN-1);
	
	// 把用户添加到列表尾部
	new->prev = head->prev;
	new->next = head;
	head->prev->next = new;
	head->prev = new;
	
	// printf("%s, %s注册成功\n", new->username, new->password);
	
	return 1;
}

/*
** 功能：登录
** head：用户链表
** user：用户名
** pass：密码
** 返回值：
** 		：成功 1
** 		：失败 0
*/ 

int user_login(UserNode *head, const char *user, const char *pass)
{
	UserNode *tmp = head->next;
	while( tmp != head )
	{
		if( strncmp(tmp->username, user,strlen(user)) == 0 )
		{
			return ( strncmp(tmp->password, pass,strlen(pass)) == 0 ) ? 1 : 0;
		}
		tmp = tmp->next;
	}
}


/*
** 功能：保存到文件
** head：用户链表
** filename：用户信息文件
*/
void user_save(UserNode *head, const char *filename)
{
	FILE *fp = fopen(filename, "w");
	if( fp == NULL )
	{
		perror("user_save fail");
		return ;
	}
	
	UserNode *tmp = head->next;
	while( tmp != head )
	{
		fprintf(fp, "%s %s\n", tmp->username, tmp->password);
		tmp = tmp->next;
	}
	fclose(fp);
}

/*
** 功能：保存到文件
** head：用户链表
** filename：用户信息文件
*/
void user_load(UserNode *head, const char *filename)
{
	FILE *fp = fopen(filename, "r");
	if( fp == NULL )
	{
		perror("user_load() fail");
		return ;
	}
	
	char user[MAX_PASSWORD_LEN] = {0}, pass[MAX_USERNAME_LEN] = {0};
	while( fscanf(fp, "%31s %63s", user, pass) == 2 )
	{
		user_register(head, user, pass);
	}
	fclose(fp);
}
void user_create(void)
{
    FILE *fp = fopen(USER_FILE,"rt");
    head1 = user_list_init();
    if (fp == NULL)
    {
        user_register(head1, "lx", "1");
        user_register(head1, "2", "2");
        user_save(head1,USER_FILE);
        user_load(head1,USER_FILE);
    }
    else
    {
        user_load(head1,USER_FILE);
    }
}